/**
 * Created by user on 17/2/13.
 */
let utils = require('../utils');
let Police = require('koa-police');
let ErrorCode = require('../enums/status');

module.exports = () => {
    let logger = utils.getLogger();
    return async (ctx, next) => {
        try {
            await next();
        } catch (err) {
            logger.error(err);
            // 登录态鉴权失败
            if (err instanceof Police.AuthenticationError) {
                logger.debug(`Rejected by ${err.policy}`);
                if (ctx.request.isAPI) {
                    return ctx.JsonResponse.error(403, '未授权');
                }
                let refer = encodeURIComponent(ctx.request.href);
                ctx.redirect(`http://passport.oa.com/site/login.html?returnUrl=${refer}`);
                return;
            }
            // api接口输入参数校验失败
            if (err.isJoi) {
                logger.error(err);
                return ctx.JsonResponse.error(ErrorCode.Parameter, err.message);
            }
            if (ctx.request.isAPI) {
                return ctx.JsonResponse.error(ErrorCode.INTERNAL, err.message);
            } else {
                ctx.status = 500;
                await ctx.redirect('/500');
            }
        }
    };
};
